<script setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useRouteListener } from '@/hooks/useRouteListener'
import { compile } from 'path-to-regexp'

const route = useRoute()
const router = useRouter()
const { listenerRouteChange } = useRouteListener()

const breadcrumbs = ref([])

const getBreadcrumb = () => {
  breadcrumbs.value = route.matched.filter(item => item.meta?.title && item.meta?.breadcrumb !== false)
}

const pathCompile = path => {
  const toPath = compile(path)
  return toPath(route.params)
}

const handleLink = item => {
  const { redirect, path } = item
  if (redirect) {
    router.push(redirect)
    return
  }
  router.push(pathCompile(path))
}

listenerRouteChange(route => {
  if (route.path.startsWith('/redirect/')) return
  getBreadcrumb()
}, true)
</script>

<template>
  <el-breadcrumb>
    <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="item.path">
      <span v-if="item.redirect === 'noRedirect' || index === breadcrumbs.length - 1" class="no-redirect">
        {{ item.meta.title }}
      </span>
      <a v-else @click.prevent="handleLink(item)">
        {{ item.meta.title }}
      </a>
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>

<style lang="scss" scoped>
.el-breadcrumb {
  line-height: 60px;

  .no-redirect {
    color: var(--el-text-color-placeholder);
  }

  a {
    font-weight: normal;
  }
}
</style>
